#include "los_config.h"
#include "lfs.h"
#include "los_fs.h"

#if (LOSCFG_SUPPORT_LITTLEFS == 1)

#define LOSCFG_LFS_MAX_MOUNT_SIZE 2

// 定义分区信息
HalLogicPartition g_halPartitions[] = {
    [FLASH_PARTITION_DATA0] = {
        .partitionDescription = "littlefs",
        .partitionStartAddr = 0,
        .partitionLength = 1024*1024*2, // size is 2M
    },
    [FLASH_PARTITION_DATA1] = {
        .partitionDescription = "vfat",
        .partitionStartAddr = 1024*1024*100,
        .partitionLength = 1024*1024*100, // size is 100M
    },
};
// 初始化文件系统，必须在内核启动之火调用fs_init
INT32 fs_init()
{
    INT32 ret;
    fs_cfg fs[LOSCFG_LFS_MAX_MOUNT_SIZE] = {0};
    INT32 lengthArray = g_halPartitions[FLASH_PARTITION_DATA0].partitionLength;
    INT32 addrArray = g_halPartitions[FLASH_PARTITION_DATA0].partitionStartAddr;
    printf("-----------fs init-----------\n");
    // 分区
    ret = LOS_DiskPartition("flash0", "littlefs", &lengthArray, &addrArray, 1);
    printf("%s: ---DiskPartition %s---\n", __func__, (ret == 0) ? "succeed" : "failed");
    if (ret != 0) {
        return -1;
    }
    // 分区参数设置
    fs[0].mount_point = "/stm32f407atk";
    fs[0].partCfg.partNo = 0;
    fs[0].partCfg.blockSize = 512; /* 4096, lfs block size */
    fs[0].partCfg.blockCount = 1024*2; /* 2048, lfs block count */
    fs[0].partCfg.readFunc = lfs_read;
    fs[0].partCfg.writeFunc = lfs_write;
    fs[0].partCfg.eraseFunc = lfs_erase;

    fs[0].partCfg.readSize = 64; /* 256, lfs read size */
    fs[0].partCfg.writeSize = 64; /* 256, lfs prog size */
    fs[0].partCfg.cacheSize = 64; /* 256, lfs cache size */
    fs[0].partCfg.lookaheadSize = 64; /* 16, lfs lookahead size */
    fs[0].partCfg.blockCycles = 64; /* 1000, lfs block cycles */
    // 使用参数格式化分区
    ret = LOS_PartitionFormat("flash0", "littlefs", &fs[0].partCfg);
    printf("%s: PartitionFormat %s\n", __func__, (ret == 0) ? "succeed" : "failed");
    if (ret != 0) {
        return -1;
    }
    // 挂载分区
    ret = mount(NULL, fs[0].mount_point, "littlefs", 0, &fs[0].partCfg);
    printf("%s: mount fs on '%s' %s\n", __func__, fs[0].mount_point, (ret == 0) ? "succeed" : "failed");
    if (ret != 0) {
        return -1;
    }
    // 创建目录
    ret = mkdir(fs[0].mount_point, 0777); /* 0777, set dir permissions */
    printf("%s: mkdir '%s' %s\n", __func__, fs[0].mount_point, (ret == 0) ? "succeed" : "failed");
    if (ret != 0) {
        return -1;
    }

    return 0;
}
#endif
